Xbasic

csv_to_json Function

Syntax

C result = csv_to_json(txt as C)

Arguments

txtCharacter

A CSV string of CR-LF delimited rows. The first row of text is assumed to be the field names. Each field in the row must be separated by a comma.

Returns

resultCharacter

A JSON string.

Description

Convert a comma-delimited CSV string to JSON.

Discussion

Convert a CSV string to JSON. Fields must be comma delimited. First row must be fields names. If a field contains a comma, enclose field in quotes. If a field contains quotes, escape quotes using two consecutive quotes.

Example

dim txt as c
txt = <<%txt%
ticker,name,price:N,change:N,mktcap,chgPct
"AAPL","Apple Inc.",402.215,"-24.025",377.7B,"-24.025 - -5.64%"
"GOOG","Google Inc.",780.37,"-13.00",257.3B,"-13.00 - -1.64%"
%txt%
 

? csv_to_json(txt)
= [
{ "ticker" : "AAPL" , "name" : "Apple Inc." , "price:N" : "402.215" , "change:N" : "-24.025" , "mktcap" : "377.7B" , "chgPct" : "-24.025 - -5.64%"} ,
{ "ticker" : "GOOG" , "name" : "Google Inc." , "price:N" : "780.37" , "change:N" : "-13.00" , "mktcap" : "257.3B" , "chgPct" : "-13.00 - -1.64%"}
]